package com.chhuang.ewcrm.ctrl;

import com.browniebytes.javafx.control.DateTimePicker;
import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.bean.TableColumnBean;
import com.chhuang.ewcrm.dao.WLogDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.WLog;
import com.chhuang.ewcrm.utils.LengthTextFilter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jfoenix.controls.JFXButton;
import javafx.beans.property.ObjectProperty;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 程序日志查询
 */
public class WLogController implements InitController{
    private final Logger logger = LoggerFactory.getLogger(WLogController.class);

    @FXML
    private TextField usernameTextField;
    @FXML
    private TextField fullnameTextField;
    @FXML
    private TextArea logContentTextArea;
    @FXML
    private TextField queryUsernameTextField;
    @FXML
    private TextField queryFullnameField;
    @FXML
    private TextField queryLogContentTextField;
    @FXML
    private DateTimePicker createTimeStartPicker;
    private ObjectProperty<LocalDateTime> createTimeStart;
    @FXML
    private DateTimePicker createTimeEndPicker;
    private ObjectProperty<LocalDateTime> createTimeEnd;
    @FXML
    private JFXButton delJFXButton;
    @FXML
    private JFXButton seachJFXButton;
    @FXML
    private TableView<WLog> tableView;
    @FXML
    private ChoiceBox<Integer> pageSizeChiceBox;
    @FXML
    private Pagination pagination;
    @FXML
    private Label pagesLabel;
    @FXML
    private Label totalLabel;

    private final LengthTextFilter lengthTextFilter = new LengthTextFilter(127);

    private final WLogDao wLogDao = App.getSession().getMapper(WLogDao.class);

    private final QueryBean<WLog> queryBean = new QueryBean<>();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initTextFiled();
        initDateTimePicker();
        initTableView();
        initButton();
    }

    /**
     * 初始化输入框
     */
    private void initTextFiled() {
        usernameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        fullnameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        queryUsernameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        queryFullnameField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
    }

    /**
     * 初始化日期控件
     */
    private void initDateTimePicker(){
        createTimeStartPicker.setPopupPreWidth(createTimeStartPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        createTimeStart = createTimeStartPicker.dateTimeProperty();
        createTimeEndPicker.setPopupPreWidth(createTimeEndPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        createTimeEnd = createTimeEndPicker.dateTimeProperty();
    }

    private WLog selectLog = new WLog();

    private TableColumnBean[] tableColumnBeans = {
            new TableColumnBean("ID","logId",false, false),
            new TableColumnBean("USERID","userId",false, false),
            new TableColumnBean("用户名","username",true),
            new TableColumnBean("姓名","fullname",true),
            new TableColumnBean("日志内容","logContent",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    String logContent = String.valueOf(o);
                    return logContent.length()>53?logContent.substring(0,50)+"...":logContent;
                }
            },
            new TableColumnBean("创建时间","createTime",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.TIME_FORMAT);
                }
            }
    };
    private void initTableView() {
        //设置列
        List<TableColumn<WLog, Object>> tableColumns = new LinkedList<>();
        for (TableColumnBean tb : tableColumnBeans){
            TableColumn<WLog, Object> tableColumn = new TableColumn<>(tb.getColumnName());
            tableColumn.setCellValueFactory(new PropertyValueFactory<>(tb.getRecordName()));
            tableColumn.setSortable(tb.isSort());
            tableColumn.setVisible(tb.isVisible());
            tableColumn.setCellFactory(new Callback<>() {
                @Override
                public TableCell<WLog, Object> call(TableColumn<WLog, Object> tableColumn) {
                    TableCell<WLog, Object> cell = new TableCell<>() {
                        @Override
                        protected void updateItem(Object o, boolean b) {
                            super.updateItem(o, b);
                            if (b || o == null)
                                this.setText(null);
                            else
                                this.setText(tb.format(o));
                        }
                    };
                    cell.setAlignment(Pos.CENTER);
                    return cell;
                }
            });
            tableColumns.add(tableColumn);
        }
        tableView.getColumns().addAll(tableColumns);

        //设置双击某一行
        tableView.setRowFactory(wCustomerTableView -> {
            TableRow<WLog> row = new TableRow<>();
            row.setOnMouseClicked(mouseEvent -> {
                if(mouseEvent.getClickCount()==2 && !row.isEmpty()){
                    selectLog = row.getItem();
                    usernameTextField.setText(selectLog.getUsername());
                    fullnameTextField.setText(selectLog.getFullname());
                    logContentTextArea.setText(selectLog.getLogContent());
                }
            });
            return row;
        });

        //设置排序
        tableView.setSortPolicy(wCustomerTableView -> {
            ObservableList<TableColumn<WLog,?>> list = wCustomerTableView.getSortOrder();
            if(list!=null && !list.isEmpty()){
                String orderby = "";
                for (TableColumn<WLog,?> tableColumn: list){
                    String property = ((PropertyValueFactory)tableColumn.getCellValueFactory()).getProperty();
                    TableColumn.SortType sortType = tableColumn.getSortType();
                    if(sortType == TableColumn.SortType.DESCENDING) property += " desc";
                    orderby += property+",";
                }
                orderby = orderby.substring(0, orderby.length()-1);
                if(StringUtils.isNotEmpty(orderby)) queryBean.setOrderBy(orderby);
                getTableData();
            }
            return true;
        });

        //每页显示多少条数据
        pageSizeChiceBox.getItems().addAll(5,10,20,50,100,150,200);
        pageSizeChiceBox.setValue(queryBean.getPageSize());

        //每页显示多少条数据选择器监听
        pageSizeChiceBox.getSelectionModel().selectedItemProperty().addListener((observableValue, integer, t1) -> {
            queryBean.setPageSize(t1);
            getTableData();
        });

        pagination.setMaxPageIndicatorCount(9);//数字按钮数量
        //点击分页按钮监听
        pagination.currentPageIndexProperty().addListener((observableValue, number, t1) -> {
            queryBean.setPageNum(t1.intValue()+1);
            logger.debug("pagintion+++"+queryBean.toString());
            getTableData();
        });

        //获取表格数据
        getTableData();

    }

    /**
     * 获取日志数据
     */
    private void getTableData() {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("create_time desc");
        }
        PageInfo<WLog> pageInfo = PageHelper.startPage(queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy()).doSelectPageInfo(() ->
                wLogDao.queryLike(queryBean.getQuery())
        );

        //总页数发生改变时从第一页开始
        if(queryBean.getPageNum()>pageInfo.getPages() && queryBean.getPageNum()!=1 ){
            queryBean.setPageNum(1);
            getTableData();
            return;
        }

        //一共多少条数据
        if(queryBean.getTotal()-pageInfo.getTotal()!=0){
            queryBean.setTotal(pageInfo.getTotal());
            totalLabel.setText(String.valueOf(queryBean.getTotal()));
        }

        //一共多少页
        if(queryBean.getPages()-pageInfo.getPages()!=0) {
            queryBean.setPages(pageInfo.getPages());
            pagesLabel.setText(String.valueOf(queryBean.getPages()));
            pagination.setPageCount(queryBean.getPages());
        }

        tableView.getItems().clear();
        if(pageInfo.getList()!=null && !pageInfo.getList().isEmpty())
            tableView.getItems().addAll(pageInfo.getList());
    }

    /**
     * 初始化按钮监听
     */
    private void initButton() {
        //点击删除
        delJFXButton.setOnAction(event -> {
            if(selectLog!=null && StringUtils.isNotEmpty(selectLog.getLogId())){
                wLogDao.deleteByEntity(selectLog);
                getTableData();
            }
            resetForm();
        });

        //查询
        seachJFXButton.setOnAction(event -> {
            WLog wLog = new WLog();
            String username = queryUsernameTextField.getText();
            wLog.setUsername(username);
            String fullname = queryFullnameField.getText();
            wLog.setFullname(fullname);
            String logContent = queryLogContentTextField.getText();
            wLog.setLogContent(logContent);

            if(!createTimeStartPicker.isVoid())
                wLog.setCreateTimeStart(DateUtil.localDateTime2Date(createTimeStart.get()));
            if(!createTimeEndPicker.isVoid())
                wLog.setCreateTimeEnd(DateUtil.localDateTime2Date(createTimeEnd.get()));

            queryBean.setQuery(wLog);
            getTableData();
        });
    }

    /**
     * 清空编辑区和selectLog
     */
    private void resetForm() {
        usernameTextField.clear();
        fullnameTextField.clear();
        logContentTextArea.clear();
        selectLog.setLogId(null);
    }

    @Override
    public void close() {

    }
}
